//
//  InfoViewController.m
//  MyLittleBrother
//
//  Created by speeda on 17/7/30.
//  Copyright © 2017年 speeda. All rights reserved.
//

#import "InfoViewController.h"
#import "JFCityViewController.h"
#import "TZImagePickerController.h"
#import "OSSImageUploader.h"
#import "NameViewController.h"

static NSString *const AccessKey = @"LTAIOeyjfgCpgPv2";
static NSString *const SecretKey = @"4cQA2kOOuPhmTaO9wFQ4kMnR90smtk";
static NSString *const BucketName = @"speeda-img";
static NSString *const AliYunHost = @"https://oss-cn-hangzhou.aliyuncs.com";

@interface InfoViewController () <UITableViewDataSource,UITableViewDelegate,JFCityViewControllerDelegate,NameViewControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *infoTableView;
@property (nonatomic, strong) NSMutableArray *infoArray;
@property (nonatomic, strong) NSMutableArray *subTitleArray;
@property (weak, nonatomic) IBOutlet UICollectionView *middleCollectionView;

@property (nonatomic, strong) UIImageView *headImgView;

@end

@implementation InfoViewController


- (void)viewWillAppear:(BOOL)animated {
    
    //设置导航条主体颜色
//    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"个人资料";
    
    [self initTableView];
}

- (void)initTableView {

    self.infoTableView.dataSource = self;
    self.infoTableView.delegate = self;
    self.infoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.infoTableView.tableFooterView = [[UIView alloc] init];
    self.infoTableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
}


#pragma mark -- 修改用户信息
- (void)requestModiuser:(NSString *)urlStr city:(NSString *)cityStr {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSString *userid = [[NSUserDefaults standardUserDefaults] objectForKey:kUserid];
    dict[@"command"] = @"modiuser";
    dict[@"userid"] = userid;
    dict[@"headimg"] = urlStr;
    dict[@"city"] = cityStr;
    
    [AFHTTPSTool POSTRequestRequestWebsite:Url AndDictionary:dict success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        
        NSDictionary *dic = responseObject;
        NSString *state = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([state isEqualToString:@"000000"]) {
            
            NSLog(@"修改用户信息 = %@",responseObject);
            if (cityStr) {
                [[NSUserDefaults standardUserDefaults] setObject:cityStr forKey:kCity];
                NSIndexPath *indexPath = [self.infoTableView indexPathForSelectedRow];
                
                UITableViewCell *cell = [self.infoTableView cellForRowAtIndexPath:indexPath];
                
                cell.detailTextLabel.text = cityStr;
            } else {
            
                [[NSUserDefaults standardUserDefaults] setObject:urlStr forKey:kHeadimg];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.headImgView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"img_touxiang"]];
                    
                });
            }
            
        } else {
            
            NSString *errorText = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [SVProgressHUD showInfoWithStatus:errorText];
        }
        
        
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}


#pragma mark -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.infoArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *personalCell = @"personalCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:personalCell];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:personalCell];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    if (indexPath.row == 0) {
        NSString *headUrlStr = [userDefault objectForKey:kHeadimg];
        self.headImgView = [[UIImageView alloc] init];
        self.headImgView.frame = CGRectMake(CGRectGetMaxX(cell.frame) - 20, 2, 40, 40);
        self.headImgView.layer.cornerRadius = 20;
        self.headImgView.layer.masksToBounds = YES;
        [self.headImgView sd_setImageWithURL:[NSURL URLWithString:headUrlStr] placeholderImage:[UIImage imageNamed:@"img_touxiang"]];
        [cell.contentView addSubview:self.headImgView];
    } else if (indexPath.row == 1) {
        NSString *mobileStr = [userDefault objectForKey:kMobile];
        cell.detailTextLabel.text = mobileStr;
    }else if (indexPath.row == 2) {
        NSString *nameStr = [userDefault objectForKey:kNickname];
        cell.detailTextLabel.text = nameStr;
        
    }else if (indexPath.row == 3) {

        NSString *cityStr = [userDefault objectForKey:kCity];
        cell.detailTextLabel.text = cityStr;
    }

    cell.textLabel.text = self.infoArray[indexPath.row];
    
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:6 delegate:nil];
        
        // You can get the photos by block, the same as by delegate.
        // 你可以通过block或者代理，来得到用户选择的照片.
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets,BOOL isSelectOriginalPhoto) {
            
            [OSSImageUploader asyncUploadImage:photos.lastObject complete:^(NSArray<NSString *> *names, UploadImageState state) {
                NSString *strUrl = [AliYunHost stringByReplacingOccurrencesOfString:@"https://" withString:@""];
                NSString *urlStr = [NSString stringWithFormat:@"https://%@.%@/%@",BucketName,strUrl,names.lastObject];
                
                [self requestModiuser:urlStr city:nil];
            }];
        }];
        
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
        
    } else if(indexPath.row == 1) {
    
//        NameViewController *nameVc = [[NameViewController alloc] init];
//        nameVc.delegate = self;
//        nameVc.titleName = @"修改账号";
//        [self.navigationController pushViewController:nameVc animated:YES];
        
    }else if( indexPath.row == 2) {
        
        NameViewController *nameVc = [[NameViewController alloc] init];
        nameVc.delegate = self;
        nameVc.titleName = @"修改昵称";
        [self.navigationController pushViewController:nameVc animated:YES];
        
    }else if (indexPath.row == 3) {
        JFCityViewController *cityViewController = [[JFCityViewController alloc] init];
        cityViewController.delegate = self;
        cityViewController.title = @"城市";
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:cityViewController];
        [self presentViewController:navigationController animated:YES completion:nil];
    }
}

#pragma mark -- NameViewControllerDelegate
-(void)nameViewControllerWithString:(NSString *)string {

    NSIndexPath *indexPath = [self.infoTableView indexPathForSelectedRow];
    
    UITableViewCell *cell = [self.infoTableView cellForRowAtIndexPath:indexPath];
    
    cell.detailTextLabel.text = string;
}


#pragma mark -- JFCityViewControllerDelegate
- (void)cityName:(NSString *)name {
    
    [self requestModiuser:nil city:name];
}


- (NSMutableArray *)infoArray {
    
    if (!_infoArray) {
        _infoArray = [NSMutableArray arrayWithObjects:@"头像",@"账号",@"昵称",@"城市", nil];
    }
    
    return _infoArray;
}

- (NSMutableArray *)subTitleArray {

    if (!_subTitleArray) {
        _subTitleArray = [NSMutableArray arrayWithObjects:@"头像",@"123456789",@"疾风剑豪",@"杭州", nil];
    }
    
    return _subTitleArray;
}


- (void)viewWillDisappear:(BOOL)animated{
    
//    [self.navigationController.navigationBar setTintColor:nil];
}


@end
